package org.jiangnantaste.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jiangnantaste.domain.Image;
import org.jiangnantaste.domain.Restaurant;
import org.jiangnantaste.util.HttpUtil;
import org.jiangnantaste.util.ImageDispose;
import org.jiangnantaste.util.ImageHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ListAllRestaurantsActivity extends ListActivity{
	private ListView myView;
	private List<Restaurant> restaurantlist;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			setTitle("江南味道");

			String url = HttpUtil.BASE_URL+"facade/listAllRestaurantsFacade";
			String result = HttpUtil.queryStringForPost(url);
	
			restaurantlist = parseRestaurantList(result);
			MyAdapter adapter = new MyAdapter(this);
			myView = new ListView(this);
			myView.setAdapter(adapter);
			setContentView(myView);
		} catch(Exception e){
			e.printStackTrace();
		}		
	}
	
	 private List<Map<String, Object>> getData(List<Restaurant> originalList) {
	        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	        
	        for (int i=0; i < originalList.size(); i++){
		         Map<String, Object> map = new HashMap<String, Object>();
		        	map.put("餐馆序号", originalList.get(i).getRestaurantId());
		        	map.put("餐馆名", originalList.get(i).getName());
		        	map.put("地址", originalList.get(i).getAddress());
		        	map.put("电话", originalList.get(i).getTelephone());
		        	list.add(map);
	        }
	        return list;
	    }
	
	public List<Restaurant> parseRestaurantList(String json) throws Exception{
		ArrayList<Restaurant> list = new ArrayList<Restaurant>();
		JSONTokener jsonParser = new JSONTokener(json);
		JSONArray arr = (JSONArray) jsonParser.nextValue(); 
		for (int i = 0; i< arr.length(); i++){
			Restaurant od = new Restaurant();
			JSONObject jo = arr.getJSONObject(i);
			od.setAddress(jo.getString("address"));
			od.setRestaurantId(jo.getLong("restaurantId"));
			od.setName(jo.getString("name"));
			od.setDescription(jo.getString("description"));
			od.setTelephone(jo.getString("telephone"));
			od.setIsactive(Boolean.parseBoolean(jo.getString("isactive")));
			long imageId = jo.getLong("imageId");
			Image img = new Image();
			if (imageId > 0L){
				JSONObject jsimg = jo.getJSONObject("image");
				img.setImageId(jsimg.getLong("imageId"));
				img.setImageName(jsimg.getString("imageName"));
				img.setPathName(jsimg.getString("pathName"));
				img.setImageData(ImageHelper.decode(jsimg.getString("imageData")));
				od.setImage(img);
				od.setImageId(imageId);
			}
			
			list.add(od);
		}
		return list;
	}
	    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
         
        Log.v("JerryDebug::ListViewClick::", (String)restaurantlist.get(position).getName());
    }

    public void showInfo(int position){
        new AlertDialog.Builder(this)
        .setTitle("江南味道")
        .setMessage(restaurantlist.get(position).toString())
        .setPositiveButton("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        })
        .show();         
    }
    
    public void refleshRestaurant(int position){
	   String url = HttpUtil.BASE_URL+"jsoncontroller/updateDeliveryOrderDeliveryPersonByEmployeeidController";
		SharedPreferences pres = getSharedPreferences("user_msg", MODE_WORLD_READABLE);
		long restautantId = restaurantlist.get(position).getRestaurantId();
		url = url + "?restaurantId=" + restautantId;

		String result = HttpUtil.queryStringForGet(url);
		try {
			restaurantlist = parseRestaurantList(result);
			myView.refreshDrawableState();
		} catch (Exception e){
			
		}
    }
     
    public final class ViewHolder{
        public TextView restaurantId;
        public TextView name;
        public TextView address;
        public TextView phone;
        public ImageView imageData;
        public Button viewBtn;
        public Button orderBtn;
    }
     
     
    public class MyAdapter extends BaseAdapter{
 
        private LayoutInflater mInflater;
         
         
        public MyAdapter(Context context){
            this.mInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            return restaurantlist.size();
        }
 
        @Override
        public Object getItem(int position) {
            return restaurantlist.get(position);
        }
 
        @Override
        public long getItemId(int position) {
        	return restaurantlist.get(position).getRestaurantId();
        }
 
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
             
            ViewHolder holder = null;
            if (convertView == null) {
                 
                holder=new ViewHolder();  
                 
                convertView = mInflater.inflate(R.layout.restaurant_list, null);
                holder.restaurantId = (TextView)convertView.findViewById(R.id.restaurantId);
                holder.name = (TextView)convertView.findViewById(R.id.restaurant_name);
                holder.address = (TextView)convertView.findViewById(R.id.restaurant_address);
                holder.phone = (TextView)convertView.findViewById(R.id.restaurant_phone);
                holder.imageData = (ImageView)convertView.findViewById(R.id.restaurant_image);
                holder.viewBtn = (Button)convertView.findViewById(R.id.view_restaurant_btn);
                holder.orderBtn = (Button)convertView.findViewById(R.id.order_restaurant_btn);
                convertView.setTag(holder);
            }else {
                 
                holder = (ViewHolder)convertView.getTag();
            }
             
             
            holder.restaurantId.setText(""+restaurantlist.get(position).getRestaurantId());
            holder.name.setText((String)restaurantlist.get(position).getName());
            holder.address.setText((String)restaurantlist.get(position).getAddress());
            holder.phone.setText(restaurantlist.get(position).getTelephone()==null?"":""+restaurantlist.get(position).getTelephone());
            if (restaurantlist.get(position).getImageId() > 0L){
            	holder.imageData.setImageBitmap(ImageDispose.getPicFromBytes(restaurantlist.get(position).getImage().getImageData(), new BitmapFactory.Options()));
            	}
            holder.viewBtn.setOnClickListener(new View.OnClickListener() {
                 
                @Override
                public void onClick(View v) {
                    showInfo(position);                 
                }
            });
            
          
             
            return convertView;
        }
         
    }
}
